package com.itheima.thread.communication.demo05;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ProducerThread implements Runnable {

    private Box box;
    private ReentrantLock reentrantLock;
    private Condition condition;

    public ProducerThread(Box box, ReentrantLock reentrantLock, Condition condition){
        this.box = box;
        this.reentrantLock = reentrantLock;
        this.condition = condition;
    }

    private int count = 0;
    @Override
    public void run() {
        while (true) {
            reentrantLock.lock();
            if (box.isFlag()) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (count % 2 == 0) {
                box.setMilkType("牛奶");
                box.setAmount("5L");
            } else {
                box.setMilkType("羊奶");
                box.setAmount("10L");
            }
            box.setFlag(true);
            condition.signal();
            reentrantLock.unlock();
            count++;
        }
    }
}
